﻿using System;
using System.Windows;
using GalaSoft.MvvmLight.Messaging;
using mal.WP7.GoogleAnalytics.Business.Tiles;
using Microsoft.Phone.Scheduler;

namespace mal.WP7.GoogleAnalytics.TileUpdateAgent
{
    public class ScheduledAgent : ScheduledTaskAgent
    {
        private static volatile bool _classInitialized;

        /// <summary>
        /// ScheduledAgent constructor, initializes the UnhandledException handler
        /// </summary>
        public ScheduledAgent()
        {
            if (!_classInitialized)
            {
                _classInitialized = true;

                // Subscribe to the managed exception handler
                Deployment.Current.Dispatcher.BeginInvoke(delegate
                {
                    Application.Current.UnhandledException += this.ScheduledAgent_UnhandledException;
                });
            }

            Messenger.Default.Register<TileUpdateCompletedMessage>(this, this.OnTileUpdateCompletedMessage);
        }        

        /// <summary>
        /// Agent that runs a scheduled task
        /// </summary>
        /// <param name="task">
        /// The invoked task
        /// </param>
        /// <remarks>
        /// This method is called when a periodic or resource intensive task is invoked
        /// </remarks>
        protected override void OnInvoke(ScheduledTask task)
        {            
            TileManager tileManager = new TileManager();
            //DateTime? lastUpdate = tileManager.GetLastTilesUpdate();
            //bool update = true;           

            //if (update)
            //{
            //    tileManager.UpdateAllTiles();
            //}
            //else
            //{
            //    NotifyComplete();
            //}

            tileManager.UpdateAllTiles();
        }

        /// <summary>Code to execute on Unhandled Exceptions</summary>
        private void ScheduledAgent_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            if (System.Diagnostics.Debugger.IsAttached)
            {
                // An unhandled exception has occurred; break into the debugger
                System.Diagnostics.Debugger.Break();
            }
        }

        private void OnTileUpdateCompletedMessage(TileUpdateCompletedMessage message)
        {
            NotifyComplete();
        }
    }
}